package com.fm.dimenstool

import org.w3c.dom.Node
import java.io.File
import javax.xml.parsers.DocumentBuilderFactory

/**
 * 解析dimes.xml文件
 *
 * 生成dp和sp的map集合
 *
 * 使用请修改file路径指向自己的dimens.xml，以达到复制生成
 */
object DimensParse {
    val mapDp = LinkedHashMap<String, Double>()

    val mapSp = LinkedHashMap<String, Double>()

    fun parseDimesXml(): Boolean {
        val factor = DocumentBuilderFactory.newInstance()
        return try {
            val tempFile = File("")
            val file = File("${tempFile.absolutePath}/app/src/main/res/values/dimens.xml")
//            val file = File("E:\\WorkSpace\\Demo_Project\\dimens_tool\\src\\main\\res\\values\\dimens.xml")
            val builder = factor.newDocumentBuilder()
            val d = builder.parse(file)
            //获取 dimen 元素列表
            val dimenList = d.getElementsByTagName("dimen")
            //循环 dimen 元素列表
            //循环resurces 节点列表
            for (j in 0 until dimenList.length) {
                val node = dimenList.item(j)
                if (node.nodeType == Node.ELEMENT_NODE) {
                    //节点名字
                    val nodeName = node.attributes.item(0).nodeValue
                    //节点值
                    val nodeValue = node.firstChild.nodeValue

                    when {
                        nodeName.contains("sp") -> {
                            val number = nodeValue.replace("sp", "").trim().toDouble()
                            mapSp[nodeName] = number
                        }
                        nodeName.contains("dp") -> {
                            val number = nodeValue.replace("dp", "").trim().toDouble()
                            mapDp[nodeName] = number
                        }
                    }
                }
            }
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

}